import React, { forwardRef, PureComponent } from 'react'
import { Button, DatePicker, Form, message, Radio, Select, TimePicker } from 'antd'
import moment from 'moment'
import { connect } from '@umijs/max'
import { gethours, getminute, getmonth, getWeek } from '@/utils/helper'
import { querySaveScheduleReq, queryVNodeDetailReq } from '../../../api'
import styles from './index.less'

const { Option } = Select

class DispatchConf extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      spreadSta: false,
      currentTargetNode: {},
      cycle: null,
      isShowEffectiveDate: true,
      isShowStartTime: true,
      open: false,
    }
    this.configurationForm = React.createRef()
  }

  UNSAFE_componentWillUpdate(nextProps) {
    if (nextProps.currentTargetNode != this.props.currentTargetNode) {
      // eslint-disable-next-line react/no-will-update-set-state
      this.setState(
        {
          currentTargetNode: nextProps.currentTargetNode,
        },
        () => {
          const { currentTargetNode } = this.state
          const { id, nodeType } = currentTargetNode || {}
          if (nodeType == 12) {
            this.getDetail(id)
          }
        },
      )
    }
  }

  getDetail = (id) => {
    const params = {
      nodeId: id,
    }
    queryVNodeDetailReq(params).then((data = {}) => {
      this.setState({
        // eslint-disable-next-line react/no-unused-state
        data,
        // isShowEffectiveDate: !!(data.effectiveDateStart && data.effectiveDateEnd),
        // isShowStartTime: !!(data.startTimeHour != null && data.startTimeMin != null && data.endTimeHour != null && data.endTimeMin != null),
      })
      if (data) {
        const {
          effectiveDateStart, effectiveDateEnd, cycle, startTimeHour, startTimeMin, endTimeHour, endTimeMin, execPoint, cycleDependency,
        } = data || {}

        // 单独设为变量，避免eslint报错
        const startTimeStr = `${startTimeHour}:${startTimeMin}`
        const endTimeStr = `${endTimeHour}:${endTimeMin}`

        this.setState({ cycle })

        // 如果没有开始时间把当天设置成默认时间
        const effectiveDateStartTemp = !effectiveDateStart ? moment(new Date().toLocaleDateString(), 'YYYY-MM-DD') : moment(effectiveDateStart, 'YYYY-MM-DD')

        const effectiveDateEndTemp = (!effectiveDateEnd || effectiveDateEnd === '2099-12-31 23:59:59') ? null : moment(effectiveDateEnd, 'YYYY-MM-DD')

        this.configurationForm?.current?.setFieldsValue({
          cycleDependency,
          cycle,
          // effectiveDate: [
          //   effectiveDateStart && moment(effectiveDateStart, 'YYYY-MM-DD'),
          //   effectiveDateEnd && moment(effectiveDateEnd, 'YYYY-MM-DD'),
          // ],
          effectiveDate: [
            effectiveDateStartTemp,
            effectiveDateEndTemp,
          ],
          startTime: ((cycle == 0 || cycle == 1 || cycle == 2)
            ? moment(startTimeStr, 'HH:mm') : [
              moment(startTimeStr, 'HH:mm'),
              moment(endTimeStr, 'HH:mm'),
            ]),
          execPoint: execPoint?.split(','),
        })
      }
    })
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  toggleDispatchConf = (spreadStaParams = undefined, isClear = false) => {
    if (this.state.spreadSta) {
      isClear && this.configurationForm?.current?.resetFields()
    }
    this.setState((prevState) => ({
      spreadSta: spreadStaParams != undefined ? spreadStaParams : !prevState.spreadSta,
    }))
  };

  valuesChange = (value, allValues) => {
    const key = Object.keys(value)[0]
    if (key == 'cycle') {
      this.configurationForm?.current?.resetFields(['startTime']) // 重置
      this.configurationForm?.current?.resetFields(['execPoint']) // 重置
      this.setState({
        cycle: allValues.cycle,
      })
    }
  }

  saveConf = () => {
    const { currentTargetNode } = this.state
    const { id } = currentTargetNode || {}
    // 当前选中的工作流 activeKey 即为 工作流id
    const { activeKey } = this.props || {}
    this.configurationForm.current.validateFields().then(values => {
      const effectiveDateStart = values?.effectiveDate?.[0]?.format('YYYY-MM-DD') || null
      const effectiveDateEnd = values?.effectiveDate?.[1]?.format('YYYY-MM-DD') || '2099-12-30'

      if (!effectiveDateStart) {
        message.warn('生效日期的开始时间不能为空')
        return null
      }

      let startTime = null
      let endTime = null
      if (values.cycle == 0 || values.cycle == 1 || values.cycle == 2) {
        startTime = values?.startTime?.format('HH:mm')?.split(':') || null
      } else if (values.cycle == 3 || values.cycle == 4) {
        startTime = values?.startTime[0]?.format('HH:mm')?.split(':') || null
        endTime = values?.startTime[1]?.format('HH:mm')?.split(':') || null
      }

      this.setState({
        saveLoading: true,
      })

      const params = {
        taskFlowId: activeKey,
        nodeId: id,
        effectiveDateStart: effectiveDateStart ? `${effectiveDateStart} 00:00:00` : '',
        effectiveDateEnd: effectiveDateStart ? `${effectiveDateEnd} 23:59:59` : '',
        cycle: values.cycle,
        startTimeHour: startTime ? startTime[0] : '',
        startTimeMin: startTime ? startTime[1] : '',
        endTimeHour: endTime ? endTime[0] : '',
        endTimeMin: endTime ? endTime[1] : '',
        cycleDependency: values.cycleDependency || values.cycleDependency == 0 ? values.cycleDependency : '',
        execPoint: Array.isArray(values.execPoint)
          ? values.execPoint
            .sort((a, b) => a - b)
            .join()
          : values.execPoint,
      }
      querySaveScheduleReq(params).then((res) => {
        const { msg, status } = res
        this.setState({
          saveLoading: false,
        })
        if (status == 200) {
          message.success('操作成功')
          this.toggleDispatchConf()
          this.props?.detailTaskFlow()
        } else {
          message.error(msg || '服务端错误')
        }
      })
    })
  }

  handleOpenChange = (open) => {
    this.setState({
      open,
    })
  }

  handleDate = () => {
    const { currentDate } = this.state
    const { effectiveDate } = this.configurationForm.current.getFieldsValue(['effectiveDate'])

    this.setState({ open: false })
    this.configurationForm.current.setFieldsValue({
      effectiveDate: [currentDate?.[0] || effectiveDate?.[0], null],
    })
  }

  handleCalendarChange = (dates) => {
    this.setState({
      currentDate: dates,
    })
  }

  render() {
    const {
      spreadSta, cycle, saveLoading, isShowEffectiveDate, isShowStartTime,
    } = this.state
    const { scheduleStatus, xxlJobId } = this.props
    const disabled = scheduleStatus === 0 && xxlJobId !== null
    return (
      <div className={`${styles.node_detail} ${spreadSta ? styles.spread : ''}`}>
        <div className={styles.node_detail_column}>调度配置</div>
        <Form
          className={styles.form}
          colon={false}
          layout="vertical"
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          onValuesChange={this.valuesChange}
          ref={this.configurationForm}
        >
          {
            // 后端要求，effectiveDate为空，则不显示
            isShowEffectiveDate && (
              <Form.Item
                label="生效日期"
                name="effectiveDate"
                // rules={[{ required: true, message: '请选择生效日期' }]}
              >
                {/*<DatePicker.RangePicker style={{ width: '100%' }} />*/}
                <DatePicker.RangePicker
                  disabled={disabled}
                  open={this.state.open}
                  style={{ width: '100%' }}
                  placeholder={['开始时间', '无限制']}
                  onOpenChange={this.handleOpenChange}
                  renderExtraFooter={() => (<div className={styles.extra_footer_wrap}><span onClick={this.handleDate}>无限制</span></div>)}
                  onCalendarChange={this.handleCalendarChange}
                />
              </Form.Item>
            )
          }
          <Form.Item
            label="调度周期"
            name="cycle"
            rules={[{ required: true, message: '请选择调度周期' }]}
          >
            <Select placeholder="请选择调度周期" disabled={disabled}>
              <Option key={0} value={0}>月</Option>
              <Option key={1} value={1}>周</Option>
              <Option key={2} value={2}>天</Option>
              <Option key={3} value={3}>小时</Option>
              <Option key={4} value={4}>分钟</Option>
            </Select>
          </Form.Item>
          {/* // 后端要求，startTime为空，则不显示 */}
          {cycle == 0 || cycle == 1 || cycle == 2 && isShowStartTime
            ? (
              <Form.Item
                label="执行时间"
                name="startTime"
                rules={[{ required: true, message: '请选择执行时间' }]}
              >
                <TimePicker format="HH:mm" style={{ width: '100%' }} disabled={disabled} />
              </Form.Item>
            ) : null}
          {cycle == 3 || cycle == 4 && isShowStartTime ? (
            <Form.Item
              label="执行时间"
              name="startTime"
              rules={[{ required: true, message: '请选择执行时间' }]}
            >
              <TimePicker.RangePicker format="HH:mm" style={{ width: '100%' }} disabled={disabled} />
            </Form.Item>
          ) : null}
          {cycle == 0 || cycle == 1 || cycle == 3 || cycle == 4 ? (
            <Form.Item
              label="调度间隔"
              name="execPoint"
              rules={[{ required: true, message: '请选择调度间隔' }]}
            >
              {/* <Select mode={cycle == 0 || cycle == 1 ? 'multiple' : 'none'} placeholder="请选择调度间隔"> */}
              <Select mode={cycle === 0 || cycle === 1 ? 'multiple' : 'none'} placeholder="请选择调度间隔" disabled={disabled}>
                {cycle == 0
                && getmonth().map((item) => (
                  <Option name={item.name} key={item.id}>
                    {item.name}
                  </Option>
                ))}
                {cycle == 1
                && getWeek().map((item) => (
                  <Option name={item.name} key={item.id}>
                    {item.name}
                  </Option>
                ))}
                {cycle == 4
                && getminute().map((item) => (
                  <Option name={item.name} key={item.id}>
                    {item.name}
                  </Option>
                ))}
                {cycle == 3
                && gethours().map((item) => (
                  <Option name={item.name} key={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          ) : null}
          <Form.Item
            label="跨周期依赖"
            name="cycleDependency"
            rules={[{ required: true, message: '请选择跨周期依赖' }]}
          >
            <Radio.Group disabled={disabled}>
              <Radio value={0}>不依赖上一周期</Radio>
              <Radio value={1}>等待上一周期结束</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
        <div className={styles.footer}>
          <Button className={styles.btn} onClick={() => { this.toggleDispatchConf() }}>取消</Button>
          {
            !disabled && (
              <Button className={styles.btn} loading={saveLoading} type="primary" onClick={this.saveConf}>发布</Button>
            )
          }
        </div>
      </div>
    )
  }
}

class WrappedComponentRef extends PureComponent {
  render() {
    const { forwardedRef, ...rest } = this.props
    return (
      <DispatchConf ref={forwardedRef} {...rest} />
    )
  }
}

const IComponent = connect(({ flowDev }) => ({ ...flowDev }))(WrappedComponentRef)

export default forwardRef((props, ref) => <IComponent {...props} forwardedRef={ref} />)
